package com.amx.controller;

import com.alibaba.fastjson.JSON;
import com.amx.Pojo.QueryInfo;
import com.amx.Pojo.User;
import com.amx.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * @author 一只安慕嘻
 * @create 2021-08-04 15:57
 */


@RestController
public class UserController {
    
    @Autowired
    UserDao userDao;

    @RequestMapping("/alluser")
    public String getUserList(QueryInfo queryInfo){
        // 获取最大列表数和当前编号
        int numbers = userDao.getUserCounts("%" + queryInfo.getQuery() + "%");
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();

        List<User> users = userDao.getAllUser("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();

        res.put("numbers",numbers);
        res.put("data",users);
        return JSON.toJSONString(res);
    }

    @RequestMapping("/updateState")
    public String updateState(@RequestParam("id") Integer id,@RequestParam("state")Boolean state){
        int i = userDao.updateState(id, state); // 指定update后返回成功修改的行数（虽然这里只修改了一行，要么是0要么是1
        return i>0 ? "success":"error";
    }

    @RequestMapping("/adduser")
    public String addUser(@RequestBody User user){
        user.setRole("普通用户");
        user.setState(false);
        int i = userDao.addUser(user);
        return i>0?"success":"error";
    }

    @RequestMapping("/deleteuser")
    public String deleteUser(@RequestParam("id") int id){
        int i = userDao.deleteUser(id);
        return i>0?"success":"error";
    }

    @RequestMapping("/updateUser")
    public String getUpdateUser(@RequestParam("id") int id){
        User updateUser = userDao.getUpdateUser(id);
        return JSON.toJSONString(updateUser);
    }

    @RequestMapping("/editUser")
    public String editUser(@RequestBody User user){
        int i = userDao.editUser(user);
        return i>0?"success":"error";
    }

}
